package com.nf.health.app.utils.music;

import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.widget.SeekBar;
import android.widget.TextView;

import com.nf.health.app.utils.BigDecimalUtils;
import com.nf.health.app.utils.LogUtil;
import com.nf.health.app.utils.Player;

import java.text.SimpleDateFormat;
import java.util.TimeZone;

/**
 * Created by fei on 2016/11/12.
 * 音乐在线播放  工具类
 * //http://pay.iteye.com/blog/848040
 */

public class MusicPlay {
    private static final String TAG = "yuyahao";
    private static Player player;
    private static MusicPlay musicPlay;
    private String URLMUSIC = "http://abv.cn/music/红豆.mp3";
    private String URLMUSIC1 = "http://abv.cn/music/红豆.mp3";
    private Context context;
    private static PlayStatus isPlaystatic  = PlayStatus.NOPLAY;//播放状态:默认0不播放,  1:开始博播放 ，2是暂停播放 ，3：是播放完毕
    private static SimpleDateFormat formatter;
    //private  SeekBar sb_music_progress;//当前播放的拖动条
    public enum  PlayStatus{
        NOPLAY(0),//默认0不播放
        PLAYING(1),//,1:开始博播放
        PAUSE(2),//，2是暂停播放
        FINISH(3);//3：是播放完毕

        private int status;
        PlayStatus(int status) {
            this.status = status;
        }

        public int getStatus() {
            return status;
        }

        public void setStatus(int status) {
            this.status = status;
        }
    }

    public MusicPlay(Context context) {
        this.context = context;
    }

    public String getURLMUSIC() {
        return URLMUSIC;
    }

    public void setURLMUSIC(String URLMUSIC) {
        this.URLMUSIC =  URLMUSIC;
    }

    public static void  setPlayStatus(PlayStatus isPlaystatic){
        MusicPlay.isPlaystatic = isPlaystatic;
    }
    public PlayStatus getPlayStatus(){
        return this.isPlaystatic;
    }
    public static MusicPlay getInstance(Context context) {
        if (musicPlay == null) {
            musicPlay = new MusicPlay(context);
            formatter = new SimpleDateFormat("mm:ss");
            formatter.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
        }
        return musicPlay;
    }

     public  MusicPlay setMySeekListener(SeekBar sb_music_progress){
          sb_music_progress.setOnSeekBarChangeListener(new SeekBarChangeEvent());
          player  = new Player(sb_music_progress);
         initSetMediaPlaylistener();
          return musicPlay;
     }
    public  MusicPlay setMySeekProgressListener(MySeekProgressListener mySeekProgressListener){
         this.mySeekProgressListener = mySeekProgressListener;
          return musicPlay;
     }
    private static MySeekProgressListener mySeekProgressListener;
    public interface  MySeekProgressListener{
       void onMySeekProgressData(String totleTime, String currentTime,int finishStatus);
    }

    /**
     * 是否在进行播放
     * @return
     */
    public boolean isPlayIng(){
       return player.mediaPlayer.isPlaying();
    }

    /**
     * 释放资源
     */
    public void release(){
        player.mediaPlayer.release();
    }

    public void play() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (player.mediaPlayer.isPlaying() || getPlayStatus() == PlayStatus.PLAYING) {
                    player.pause();
                    setPlayStatus(PlayStatus.PAUSE);
                } else if(getPlayStatus() == PlayStatus.NOPLAY || getPlayStatus() == PlayStatus.FINISH){
                    if(getPlayStatus() == PlayStatus.FINISH){
                        player.mediaPlayer.reset();//重置MediaPlayer到初始化状态
                        player.mediaPlayer.seekTo(0);//须将播放时间设置到0；这样才能在下次播放是重新开始，否则会继续上次播放
                    }
                    player.playUrl(URLMUSIC);
                    setPlayStatus(PlayStatus.PLAYING);
                }else if(getPlayStatus() == PlayStatus.PAUSE){
                    player.start();//继续播放
                    setPlayStatus(PlayStatus.PLAYING);
                }
            }
        }).start();
    }

    /**
     * 开始播放
     */
    public void startPlay() {
        new Thread(new Runnable() {
            @Override
            public void run() {

            }
        }).start();
    }
    /**
     * 停止播放
     */
    public void stopPlay() {

    }
    /**
     * 继续播放
     */
    public void continuePlay() {

    }
    private static void initSetMediaPlaylistener(){
        /*player.mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                Long totleLong = new Long((long) player.mediaPlayer.getDuration());
                mySeekProgressListener.onMySeekProgressData(totleLong,0L,100);
                LogUtil.i(TAG, mp.getDuration()+"我已完成啦！！！！");
            }
        });*/
        player.mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
            @Override
            public void onBufferingUpdate(MediaPlayer mp, int percent) {

                Long totleLong = new Long((long) player.mediaPlayer.getDuration());
                Long currentLong = new Long((long) player.mediaPlayer.getCurrentPosition());
                String totleTime = formatter.format(mp.getDuration());
                String currentTime = formatter.format((mp.getCurrentPosition()));
                LogUtil.e(TAG,"totle:  " +totleTime+"当前：  " + currentTime);
                if(mp.isPlaying()){//减少误差，避免得到getDuration（）的时间出问题---->在这里花费了好多的时间
                    mySeekProgressListener.onMySeekProgressData(totleTime,currentTime,0);
                    if(totleTime.equals(currentTime)){//用这样的方式判断完成，减少时间的误差
                        LogUtil.e(TAG,"我进来啦！！！");
                        setPlayStatus(PlayStatus.FINISH);
                        player.mediaPlayer.pause();
                        // player.mediaPlayer.release();
                    }
                }
           //     LogUtil.i(TAG, mp.getCurrentPosition()+"------:  " +percent+"   totle:  "  +totle+"  current: " + current);
            }
        });
    }

    public class SeekBarChangeEvent implements SeekBar.OnSeekBarChangeListener {
        int progress;

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            LogUtil.e(TAG,"totle:  " +player.mediaPlayer.getDuration());
            //this.progress  = progress * player.mediaPlayer.getDuration() / seekBar.getMax();
             this.progress = BigDecimalUtils.getMathRound(progress * player.mediaPlayer.getDuration(),seekBar.getMax());
            /*Long totleLong = new Long((long) player.mediaPlayer.getDuration());
            Long currentLong = new Long((long) player.mediaPlayer.getCurrentPosition());
            SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
            formatter.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
            String hms = formatter.format(totleLong);
            String hms2 = formatter.format(currentLong);
            LogUtil.e(TAG,"totle:  " +hms+"剩余：  " + hms2);
            mySeekProgressListener.onMySeekProgressData(totleLong,currentLong);
            if(currentLong == totleLong){
                setPlayStatus(PlayStatus.FINISH);
            }*/
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            player.mediaPlayer.seekTo(progress);
           if(getPlayStatus() == PlayStatus.FINISH) {
               play();
           }
        }

    }

    /**
     * 销毁时
     */
    public void onDestroy() {
        if (player != null && player.mediaPlayer.isPlaying()) {
            player.stop();
//            player.mediaPlayer.pause();
            player = null;
        }
        setPlayStatus(PlayStatus.NOPLAY);
    }

   public void palyByMobileSevice(){
        Intent intent = new Intent();
        Uri uri = Uri.parse(URLMUSIC);
        intent.setDataAndType(uri, "audio/mp3");//  intent.setDataAndType(uri, "audio/*");这里可以改成audio/mp3
        intent.setAction(Intent.ACTION_VIEW);
        context.startActivity(intent);
    }


}
